Queue

FIFO data structure

Array: 
Assumption: the first n elements of the queue are occupying the first n positions of the array

Option#1: If the front of the queue is stored at index 0

dequeue requires O(n) time
enqueue requires O(1) time

Option#2: Let the rear element occupy the first position in the array

dequeue requires O(1) time
enqueue requires O(n) time

To deal with the above limitations: 
1. We introduce two additional variables: 
front the index of the front element ==> front = 0
rear the index of the next available cell within the array

	front	rear
0	1	2
null	4	null

2. Relax the assumption stating that n elements must occupy the first n positions in the queue
drifting queue. 

=> Problem: If we enqueue and dequeue the same element n different times => front would assume an 
invalid index value
			front = rear = 3
0	1	2
null	null	null

Solution: let front and rear wrap around the end of the array when they get to it

rear = rear + 1 % 3 (array.length)
front = front + 1 % 3

=> circular drifiting array used to implement the queue. 

front = rear
0	1	2
3	4	5

It is very hard to differentiate between the cases of an empty queue and a full one. 
Solution: maintain a variable reflecting the current size of the queue. 

Procedure: 
1.a) Create the Queue ADT
1.b) Create the QueueException class
1.c) Create the ArrayBasedQueue implementation
1.d) Test ArrayBasedQueue

2) Use the queue to solve a problem: Josephus Problem

		
Time complexity: O(n k) where n is the number of players, and the token is being passed around the 
circle k times before we ring the bell
Space complexity: O(n)

LeetCode 1823

Josephus recurrence relation: 
denote the position of the winner by J(n, k) when there are n players 

J(n, k) = (J(n-1, k) + (k - 1)) % n + 1

k = 1

n = 41 = 32 (2^a) + 9 (L)

Position of the winner = 2 L + 1 = 2*9 + 1 = 19

Informal assignment: finding the largest power of two that is smaller than a given value in O(1) time

- Singly linked lists

Nodes as positions

  -> 	  -> null
|	|
e1	e2

Head: this is the first node/position in the singly linked list
Tail: this is the node/position whose next pointer is null.




































































